package com.gx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gx.entity.dto.CreateJobTaskDto;
import com.gx.service.JobService;
import com.gx.utils.CronUtil;
import com.gx.utils.XxlJobUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @ClassName JobTaskUtils
 * @Author lpj
 * @Date 2022/10/28 18:01
 **/
@Service
@Slf4j
public class JobServiceImpl implements JobService {

    @Value("${xxl.job.executor.jobGroup}")
    private String jobGroup;

    @Override
    public Integer saveTask(CreateJobTaskDto dto) {
        //查询列表数据
        String cropExp = CronUtil.createCronExpression(dto);
        String jobDesc = CronUtil.createDescription(dto);
        JSONObject requestInfo = new JSONObject();
        //执行器
        requestInfo.put("jobGroup", jobGroup);
        // 任务描述
        requestInfo.put("jobDesc", jobDesc);
        //表达式
        requestInfo.put("cronGen_display", cropExp);
        requestInfo.put("schedule_conf_CRON", cropExp);
        requestInfo.put("scheduleConf", cropExp);
        // 执行器，任务Handler名称
        requestInfo.put("executorHandler", dto.getExecutorHandler());
        // 任务参数
        requestInfo.put("executorParam", dto.getParam());

        requestInfo.put("author", "admin");
        //调度类型
        requestInfo.put("scheduleType", "CRON");
        //运行模式
        requestInfo.put("glueType", "BEAN");
        // 执行器路由策略
        requestInfo.put("executorRouteStrategy", "FIRST");
        // 阻塞处理策略
        requestInfo.put("executorBlockStrategy", "SERIAL_EXECUTION");
        // 负责人
        // 报警邮件
        requestInfo.put("alarmEmail", "859630097@qq.com");
        // 任务执行超时时间，单位秒
        requestInfo.put("executorTimeout", 0);
        // 失败重试次数
        requestInfo.put("executorFailRetryCount", 1);
        //重试策略
        requestInfo.put("misfireStrategy", "DO_NOTHING");
        JSONObject res = XxlJobUtil.addJob(requestInfo);
        //修改任务参数 把id放入
        // 执行器主键ID
        requestInfo.put("executorParam", "JobId=" + res.get("content"));
        requestInfo.put("id", Integer.valueOf(res.get("content").toString()));
        XxlJobUtil.updateJob(requestInfo);
        //加入任务成功之后直接启动
        XxlJobUtil.startJob((res.getInteger("content")));
        return res.getInteger("content");
    }

}
